package tron

import (
	"fisherman/common/crypte/aes"
	"fisherman/common/event"
	"fisherman/common/http"
	"fisherman/main/cfg"
	"fisherman/main/db"
	"fmt"
	"github.com/tidwall/gjson"
	"time"
)

// 查询能量余额
func QueryEnergyBalance(address string) (balance float64) {
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/getaccountresource", map[string]any{"address": address, "visible": true})
	//log.Infof("getaccountresource:%s", rsp)
	rspData := gjson.Parse(rsp)
	energyLimit := rspData.Get("EnergyLimit").Float()
	energyUsed := rspData.Get("EnergyUsed").Float()
	return energyLimit - energyUsed
}

func RentEnergyFromThirdPlatform(fromAddr, fromAddrKey string, needTRX float64) (log string, success bool) {
	if len(db.Cfg_rent_energy_address) != 34 {
		log += "RentEnergyFromThirdPlatform() 能量租赁地址未配置"
		return
	}
	log += fmt.Sprintf("%s开始给%s转%fTRX租赁能量\n", fromAddr, db.Cfg_rent_energy_address, needTRX)
	lingqianKey := CheckMnemonicOrKey(aes.DecryptString(db.Cfg_pocket_key, cfg.Cfg.AESKey))
	trxBalance := QueryTRXBalance(fromAddr)
	if trxBalance < needTRX+1 {
		if len(db.Cfg_pocket_addr) != 34 {
			log += "RentEnergyFromThirdPlatform() 零钱地址未配置"
			return
		}
		rechargeTRXAmount := needTRX + 1 - trxBalance
		if db.Cfg_pocket_addr == fromAddr {
			log += "零钱地址TRX不足，需要给零钱地址兑换TRX\n"
			return
		}
		log += fmt.Sprintf("TRX%f不足%f，开始从零钱地址充值%f（比配置多1TRX防止带宽不足转账失败）\n", trxBalance, needTRX+1, rechargeTRXAmount)
		_, _, l, suc := TransferTRX(db.Cfg_pocket_addr, lingqianKey, fromAddr, rechargeTRXAmount)
		log += l
		if !suc {
			log += "充值TRX失败\n"
			return
		}
		log += "充值TRX成功，继续租赁能量\n"
	}

	preBalance := QueryEnergyBalance(fromAddr)
	_, _, l, suc2 := TransferTRX(fromAddr, fromAddrKey, db.Cfg_rent_energy_address, needTRX)
	log += l
	if !suc2 {
		log += "给第三方转TRX失败\n"
		return
	}
	//等待到账
	rentSuccess := false
	for i := 0; i < 30; i++ {
		time.Sleep(time.Second)
		newBalance := QueryEnergyBalance(fromAddr)
		if newBalance > preBalance+10000 {
			rentSuccess = true
			break
		}
	}
	if !rentSuccess {
		log += "等待不到能量到账\n"
		event.Emit(event.Ev_RentEnergyResult, false)
		return
	}
	log += "能量租赁成功\n"
	event.Emit(event.Ev_RentEnergyResult, true)
	success = true
	return
}
